package com.aispeech.aitv.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.aispeech.aitv.R;
import com.aispeech.aitv.camera.CameraUtils;
import com.aispeech.aitv.camera.CameraUtils.TakePhotoResultListener;
import com.aispeech.aitv.voice.MyEngineListener;
import com.aispeech.aitv.voice.VoiceEngineManage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity {

    private final String TAG = "MainActivity";
    private ListView mLvShareType;
    private EditText mEtShowInput;
    private SurfaceView mSfvCamera;
    private SurfaceHolder mSfh;
    private ImageView mImvShowPhoto;
    private Camera mCamera;
    private MsgReceiver msgReceiver;

    private int[] imageId = new int[]{R.drawable.wechat_timeline,
        R.drawable.wechat_friend};
    private String[] title = new String[]{"发朋友圈", "分享朋友"};
    private List<Map<String, Object>> listitem = new ArrayList<>();

    //    private Handler mHandler = new Handler();


    //    private final long VAD_PAUSE_TIME_FOR_RECORD = 1200;
    private final String TV_WX_SHARE = "tv.wx.share";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        showCameraPreview();
        VoiceEngineManage.getInstance().initAllEngine(new MyEngineListener() {
            @Override
            public void onAsrResult(String result, boolean isFinish) {
                Log.d(TAG, "onAsrResult with: result = " + result + ", isFinish = " + isFinish + "");
                if (isFinish) {
                    //最后识别结果
                    VoiceEngineManage.getInstance().startWakeup();
                }
                updateInputText(result);
            }

            @Override
            public void onWakeupResult(String result) {
                Log.d(TAG, "onWakeupResult with: result = " + result + "");

                onCall(result, "");
            }

            @Override
            public void onInitResult(String result) {
                Log.d(TAG, "onInitResult with: result = " + result + "");
                if ("success".equals(result)) {
                    //语音主件加载完毕
                    VoiceEngineManage.getInstance().playTTS("语音加载完毕");
                    //开启唤醒
                    VoiceEngineManage.getInstance().startWakeup();
                }
            }
        });

        //register receiver
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("dui.intent.action.init_complete");
        registerReceiver(msgReceiver, intentFilter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
        stopCamera();
        VoiceEngineManage.getInstance().destroyEngine();
    }


    public void onCall(String topic, String data) {
        Log.d(TAG, "onCall with: topic = " + topic + ", data = " + data + "");

        if ("ni zhen bang".equals(topic)) {
            //自拍
            CameraUtils.getInstance().takePhoto(new TakePhotoResultListener() {
                @Override
                public void success(Bitmap bitmap) {
                    mImvShowPhoto.setImageBitmap(bitmap);
                    //重新开启预览
                    CameraUtils.getInstance().startPreview(mSfh);
                }

                @Override
                public void failed(String errInfo) {
                    //todo 拍照失败
                    VoiceEngineManage.getInstance().playTTS(errInfo);
                    //重新开启预览
                    CameraUtils.getInstance().startPreview(mSfh);

                }
            });

            VoiceEngineManage.getInstance().startWakeup();

        } else if ("ji lu xin qing".equals(topic)) {
            //记录心情
            updateInputText("");
            //开识别
            try {
                VoiceEngineManage.getInstance().startAsr();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("fen xiang hao you".equals(topic)) {
            //分享给微信好友

            VoiceEngineManage.getInstance().startWakeup();

        } else if ("fa peng you quan".equals(topic)) {
            //分享微信朋友圈
            //将图片和文字上传到服务器, 服务端将图片路径推给手机, 手机端app收到推送后发起分享朋友圈操作
            //当前先放在一个手机上简单实现
            String input = mEtShowInput.getText().toString();
            Intent i = new Intent(TV_WX_SHARE);
            i.putExtra("share_type", "timeline");
            File pf = CameraUtils.getInstance().getPhotoFile();
            if (null != pf) {
                Log.d(TAG, "onCall: pf path = " + pf.getAbsolutePath());
                Log.d(TAG, "onCall: pf name = " + pf.getName());
                i.putExtra("photo", pf.getAbsolutePath());

                if (TextUtils.isEmpty(input)) {
                    //只发图片

                } else {
                    //发送图文
                    i.putExtra("input", mEtShowInput.getText().toString().trim());
                }
            } else {
                if (TextUtils.isEmpty(input)) {
                    //啥都没记录
//                    playTTS("您好像啥都没记录哦!");
                    return;
                } else {
                    //发送文字
                    i.putExtra("input", mEtShowInput.getText().toString().trim());
                }
            }
            MainActivity.this.sendBroadcast(i);
        }
    }


    private void updateInputText(final String input) {
        Log.d(TAG, "updateInputText with: input = " + input + "");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEtShowInput.setText(input);
            }
        });
    }

    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive: " + action);
            if ("dui.intent.action.init_complete".equals(action)) {
//                playTTS("语音已启动!");
//                DDS.getInstance().geTAGent().subscribe(Topics.WAKEUP_TOPICS, MainActivity.this);
//                mAsrEngine = DDS.getInstance().geTAGent().getASREngine();
//                initEngine();

            }
        }

    }


    private void showCameraPreview() {
        mCamera = CameraUtils.getInstance().initCamera();
        mSfh = mSfvCamera.getHolder();
        mSfh.addCallback(new Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                Log.d(TAG, "surfaceCreated: ");
//                startPreview();
                CameraUtils.getInstance().startPreview(mSfh);
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                Log.d(TAG, "surfaceChanged with: i = " + i + ", i1 = " + i1 + ", i2 = " + i2 + "");
                //停止旧的预览,开启新的预览
                mCamera.stopPreview();
//                startPreview();
                CameraUtils.getInstance().startPreview(mSfh);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                Log.d(TAG, "surfaceDestroyed: ");
                stopCamera();
            }
        });
    }


    /**
     * 停止拍照释放资源
     */
    private void stopCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        //把之前自拍照片删除
        File pf = CameraUtils.getInstance().getPhotoFile();
        if (null != pf && pf.exists()) {
            pf.delete();
        }
    }

    private void initView() {
        mLvShareType = findViewById(R.id.lv_share_type);
        mEtShowInput = findViewById(R.id.et_show_input);
        mSfvCamera = findViewById(R.id.sfv_camera);
        mImvShowPhoto = findViewById(R.id.imv_show_photo);

        for (int i = 0; i < title.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("image", imageId[i]);
            map.put("title", title[i]);
            listitem.add(map);
        }

        ListViewAdapter adapter = new ListViewAdapter(MainActivity.this, listitem);
        mLvShareType.setAdapter(adapter);
        mLvShareType.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
                Toast.makeText(MainActivity.this, "position = " + position, Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    class ListViewAdapter extends BaseAdapter {

        private Context context;
        private List<Map<String, Object>> listitem;

        public ListViewAdapter(Context context, List<Map<String, Object>> listitem) {
            this.context = context;
            this.listitem = listitem;
        }

        @Override
        public int getCount() {
            return listitem.size();
        }

        @Override
        public Object getItem(int position) {
            return listitem.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_share_type, null);
            }

            ImageView imageView = convertView.findViewById(R.id.listitem_iv);
            TextView textView = convertView.findViewById(R.id.listitem_tv);

            Map<String, Object> map = listitem.get(position);
            imageView.setImageResource((Integer) map.get("image"));
            textView.setText(map.get("title") + "");
            return convertView;
        }
    }
}
